package com.wmada.toolkit.common.secure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author will.ma
 * @date 2017/3/11
 */
public class Signature {

    private static final Logger LOGGER = LoggerFactory.getLogger(Signature.class);

    public static byte[] getKey(int keyLength) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            return secureRandom.generateSeed(keyLength);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.warn("生成Key失败", e);
        }
        return null;
    }

    public static byte[] getKey(int keyLength, byte[] seed) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(seed);
            return secureRandom.generateSeed(keyLength);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Mac mac = null;

    public Signature(String algorithm, String key) {
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm));
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("初始化 Signature of [" + algorithm + "] 失败！", e);
        } catch (InvalidKeyException e) {
            LOGGER.error("设置 Sign Key of [" + algorithm + "] 失败！", e);
        }
    }

    public Signature(String algorithm, byte[] key) {
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(new SecretKeySpec(key, algorithm));
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("初始化 Signature of [" + algorithm + "] 失败！", e);
        } catch (InvalidKeyException e) {
            LOGGER.error("设置 Sign Key of [" + algorithm + "] 失败！", e);
        }
    }

    public String getSignature(String message) {
        if (mac != null && message != null) {
            return EncodeUtils.bytes2Hex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
        } else {
            return null;
        }
    }

    public byte[] getSignature(byte[] data) {
        if (mac != null && data != null) {
            return mac.doFinal(data);
        } else {
            return null;
        }
    }

}
